import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Form, 
  Input, 
  Button, 
  Switch, 
  Select, 
  message,
  Tabs,
  Divider,
  Row,
  Col,
  Spin
} from 'antd';
import { 
  SettingOutlined, 
  UserOutlined, 
  SecurityScanOutlined, 
  BellOutlined 
} from '@ant-design/icons';
import api from '../services/api';

const { Option } = Select;
const { TabPane } = Tabs;

const SettingsPage = () => {
  const [loading, setLoading] = useState(false);
  const [fetchLoading, setFetchLoading] = useState(false);
  const [systemSettings, setSystemSettings] = useState({});
  const [securitySettings, setSecuritySettings] = useState({});
  const [notificationSettings, setNotificationSettings] = useState({});
  
  // 获取系统设置
  const fetchSettings = async () => {
    setFetchLoading(true);
    try {
      // 获取系统设置
      try {
        const response = await api.get('/settings/system');
        const settings = {};
        response.data.forEach(setting => {
          settings[setting.key] = setting.value;
        });
        
        // 分类设置
        const systemKeys = ['system_name', 'language', 'timezone', 'theme', 'page_size'];
        const securityKeys = ['session_timeout', 'password_min_length', 'login_attempt_limit', 'enable_two_factor'];
        const notificationKeys = ['email_notification', 'system_notification', 'issue_assigned', 'issue_status_changed', 'case_updated'];
        
        const system = {};
        const security = {};
        const notification = {};
        
        systemKeys.forEach(key => {
          if (settings[key] !== undefined) {
            if (key === 'page_size') {
              system[key] = parseInt(settings[key]);
            } else {
              system[key] = settings[key];
            }
          }
        });
        
        securityKeys.forEach(key => {
          if (settings[key] !== undefined) {
            if (['session_timeout', 'password_min_length', 'login_attempt_limit'].includes(key)) {
              security[key] = parseInt(settings[key]);
            } else if (key === 'enable_two_factor') {
              security[key] = settings[key] === 'true';
            } else {
              security[key] = settings[key];
            }
          }
        });
        
        notificationKeys.forEach(key => {
          if (settings[key] !== undefined) {
            notification[key] = settings[key] === 'true';
          }
        });
        
        setSystemSettings(system);
        setSecuritySettings(security);
        setNotificationSettings(notification);
        
      } catch (error) {
        console.log('设置API不可用，使用默认值:', error);
        
        // 使用默认设置
        setSystemSettings({
          system_name: 'ITS问题跟踪系统',
          language: 'zh-CN',
          timezone: 'Asia/Shanghai',
          theme: 'light',
          page_size: 20
        });
        
        setSecuritySettings({
          session_timeout: 30,
          password_min_length: 6,
          enable_two_factor: false,
          login_attempt_limit: 5
        });
        
        setNotificationSettings({
          email_notification: true,
          system_notification: true,
          issue_assigned: true,
          issue_status_changed: true,
          case_updated: false
        });
      }
    } catch (error) {
      console.error('获取设置失败:', error);
      message.error('获取设置失败');
    } finally {
      setFetchLoading(false);
    }
  };
  
  useEffect(() => {
    fetchSettings();
  }, []);

  const handleSystemSave = async (values) => {
    setLoading(true);
    try {
      // 构建设置数据
      const systemSettings = {
        system_name: values.systemName,
        language: values.language,
        timezone: values.timezone,
        theme: values.theme,
        page_size: values.pageSize.toString()
      };
      
      // 调用API
      await api.post('/settings/system/batch', {
        system_settings: systemSettings
      });
      
      message.success('系统设置保存成功');
      
      // 更新本地状态
      setSystemSettings({
        system_name: values.systemName,
        language: values.language,
        timezone: values.timezone,
        theme: values.theme,
        page_size: values.pageSize
      });
      
    } catch (error) {
      console.error('保存系统设置失败:', error);
      
      if (error.response?.status === 403) {
        message.error('没有权限修改系统设置');
      } else {
        message.error('保存系统设置失败');
      }
    } finally {
      setLoading(false);
    }
  };

  const handleSecuritySave = async (values) => {
    setLoading(true);
    try {
      const securitySettings = {
        session_timeout: values.sessionTimeout.toString(),
        password_min_length: values.passwordMinLength.toString(),
        login_attempt_limit: values.loginAttemptLimit.toString(),
        enable_two_factor: values.enableTwoFactor.toString()
      };
      
      await api.post('/settings/system/batch', {
        security_settings: securitySettings
      });
      
      message.success('安全设置保存成功');
      
      setSecuritySettings({
        session_timeout: values.sessionTimeout,
        password_min_length: values.passwordMinLength,
        login_attempt_limit: values.loginAttemptLimit,
        enable_two_factor: values.enableTwoFactor
      });
      
    } catch (error) {
      console.error('保存安全设置失败:', error);
      
      if (error.response?.status === 403) {
        message.error('没有权限修改安全设置');
      } else {
        message.error('保存安全设置失败');
      }
    } finally {
      setLoading(false);
    }
  };

  const handleNotificationSave = async (values) => {
    setLoading(true);
    try {
      const notificationSettings = {
        email_notification: values.emailNotification,
        system_notification: values.systemNotification,
        issue_assigned: values.issueAssigned,
        issue_status_changed: values.issueStatusChanged,
        case_updated: values.caseUpdated
      };
      
      await api.post('/settings/system/batch', {
        notification_settings: notificationSettings
      });
      
      message.success('通知设置保存成功');
      
      setNotificationSettings(notificationSettings);
      
    } catch (error) {
      console.error('保存通知设置失败:', error);
      
      if (error.response?.status === 403) {
        message.error('没有权限修改通知设置');
      } else {
        message.error('保存通知设置失败');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <h2>系统设置</h2>
      
      <Spin spinning={fetchLoading}>
        <Tabs defaultActiveKey="system" type="card">
        <TabPane tab={
          <span>
            <SettingOutlined />
            系统设置
          </span>
        } key="system">
          <Card>
            <Form
              layout="vertical"
              onFinish={handleSystemSave}
              initialValues={{
                systemName: systemSettings.system_name || 'ITS问题跟踪系统',
                language: systemSettings.language || 'zh-CN',
                timezone: systemSettings.timezone || 'Asia/Shanghai',
                theme: systemSettings.theme || 'light',
                pageSize: systemSettings.page_size || 20
              }}
              key={JSON.stringify(systemSettings)} // 强制重新渲染
            >
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    name="systemName"
                    label="系统名称"
                    rules={[{ required: true, message: '请输入系统名称' }]}
                  >
                    <Input placeholder="请输入系统名称" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="language"
                    label="系统语言"
                  >
                    <Select placeholder="选择系统语言">
                      <Option value="zh-CN">中文简体</Option>
                      <Option value="en-US">English</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    name="timezone"
                    label="时区设置"
                  >
                    <Select placeholder="选择时区">
                      <Option value="Asia/Shanghai">中国标准时间 (UTC+8)</Option>
                      <Option value="UTC">世界协调时间 (UTC+0)</Option>
                      <Option value="America/New_York">美国东部时间 (UTC-5)</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="theme"
                    label="主题设置"
                  >
                    <Select placeholder="选择主题">
                      <Option value="light">浅色主题</Option>
                      <Option value="dark">深色主题</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              
              <Form.Item
                name="pageSize"
                label="分页大小"
              >
                <Select placeholder="选择默认分页大小">
                  <Option value={10}>10条/页</Option>
                  <Option value={20}>20条/页</Option>
                  <Option value={50}>50条/页</Option>
                  <Option value={100}>100条/页</Option>
                </Select>
              </Form.Item>
              
              <Form.Item>
                <Button type="primary" htmlType="submit" loading={loading}>
                  保存设置
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </TabPane>
        
        <TabPane tab={
          <span>
            <SecurityScanOutlined />
            安全设置
          </span>
        } key="security">
          <Card>
            <Form
              layout="vertical"
              onFinish={handleSecuritySave}
              initialValues={{
                sessionTimeout: securitySettings.session_timeout || 30,
                passwordMinLength: securitySettings.password_min_length || 6,
                enableTwoFactor: securitySettings.enable_two_factor || false,
                loginAttemptLimit: securitySettings.login_attempt_limit || 5
              }}
              key={JSON.stringify(securitySettings)}
            >
              <Form.Item
                name="sessionTimeout"
                label="会话超时时间（分钟）"
              >
                <Select placeholder="选择会话超时时间">
                  <Option value={15}>15分钟</Option>
                  <Option value={30}>30分钟</Option>
                  <Option value={60}>1小时</Option>
                  <Option value={120}>2小时</Option>
                </Select>
              </Form.Item>
              
              <Form.Item
                name="passwordMinLength"
                label="密码最小长度"
              >
                <Select placeholder="选择密码最小长度">
                  <Option value={6}>6位</Option>
                  <Option value={8}>8位</Option>
                  <Option value={12}>12位</Option>
                </Select>
              </Form.Item>
              
              <Form.Item
                name="loginAttemptLimit"
                label="登录尝试次数限制"
              >
                <Select placeholder="选择登录尝试次数限制">
                  <Option value={3}>3次</Option>
                  <Option value={5}>5次</Option>
                  <Option value={10}>10次</Option>
                </Select>
              </Form.Item>
              
              <Form.Item
                name="enableTwoFactor"
                label="启用双因素认证"
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>
              
              <Form.Item>
                <Button type="primary" htmlType="submit" loading={loading}>
                  保存设置
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </TabPane>
        
        <TabPane tab={
          <span>
            <BellOutlined />
            通知设置
          </span>
        } key="notification">
          <Card>
            <Form
              layout="vertical"
              onFinish={handleNotificationSave}
              initialValues={{
                emailNotification: notificationSettings.email_notification || true,
                systemNotification: notificationSettings.system_notification || true,
                issueAssigned: notificationSettings.issue_assigned || true,
                issueStatusChanged: notificationSettings.issue_status_changed || true,
                caseUpdated: notificationSettings.case_updated || false
              }}
              key={JSON.stringify(notificationSettings)}
            >
              <h4>邮件通知</h4>
              <Form.Item
                name="emailNotification"
                label="启用邮件通知"
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>
              
              <Divider />
              
              <h4>系统通知</h4>
              <Form.Item
                name="systemNotification"
                label="启用系统通知"
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>
              
              <Divider />
              
              <h4>通知事件</h4>
              <Form.Item
                name="issueAssigned"
                label="问题被分配时通知"
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>
              
              <Form.Item
                name="issueStatusChanged"
                label="问题状态变更时通知"
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>
              
              <Form.Item
                name="caseUpdated"
                label="案例更新时通知"
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>
              
              <Form.Item>
                <Button type="primary" htmlType="submit" loading={loading}>
                  保存设置
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </TabPane>
      </Tabs>
      </Spin>
    </div>
  );
};

export default SettingsPage;